<script setup lang="ts">
import { computed, onMounted, ref, watch, onUnmounted, nextTick } from 'vue';
import type { Ref } from 'vue';
import { inBrowser, useRoute, useRouter } from 'vitepress';
import { OMenu, OScroller } from '@opensig/opendesign';
import DocSubMenu from '@/components/doc/DocSubMenu.vue';

import { useSearchingStore } from '@/stores/common.ts';
import { DocMenuTree, type DocMenuNodeT } from '@/utils/tree.ts';
import { useScreen } from '@/composables/useScreen.ts';
import { openWindow } from '@/utils/common.ts';
import { storeToRefs } from 'pinia';
import { useMenuStore } from '@/stores/menu.ts';

const { size } = useScreen();
const route = useRoute();
const router = useRouter();

const searchValue = ref('');
const lastSearchValue = ref('');
const emit = defineEmits(['switchVisible']);

const menuStore = useMenuStore();
const { tree, currentCategory } = storeToRefs(menuStore);
// 当前选中id
const activeVal = ref('');
// 当前展开id
const expandedArr: Ref<Array<string>> = ref([]);

const treeList = computed(() => {
  return [new DocMenuTree(currentCategory.value.config || [], currentCategory.value.base || '')];
});

const getData = () => {
  const arr = decodeURIComponent(route.path).split('.');
  activeVal.value = arr.slice(0, arr.length - 1).join('.');
  nextTick(() => {
    if (inBrowser) {
      listenScroll();
      const node = tree.value.getNode(tree.value.root, activeVal.value);
      expandedArr.value = [];
      expand(node);
    }
  });
};

watch(
  () => route.path,
  () => {
    getData();
  }
);

onMounted(() => {
  getData();
});

const expand = (val: DocMenuNodeT) => {
  if (val && val.parent) {
    expandedArr.value.push(val.parent.id);
    expand(val.parent);
  }
};

// -------------------- 动态改变左侧目录的高度 --------------------
const oscrollerDom = ref();
const height = ref();

const listenScroll = () => {
  const app = document.querySelector('#app');
  const headerHeight = app?.firstElementChild?.offsetHeight || 64; // 头部高度
  const scrollHeight = oscrollerDom.value.scrollHeight; // 页面高度
  const scrollTop = oscrollerDom.value.scrollTop; // 滚动高度
  const clientHeight = document.body.clientHeight; // 一屏高度
  if (scrollHeight - scrollTop - clientHeight < 0) {
    const h = scrollTop + clientHeight - scrollHeight;
    height.value = `calc(100% - ${headerHeight}px - ${h}px)`;
  } else {
    height.value = `calc(100% - ${headerHeight}px)`;
  }
};

onMounted(() => {
  if (inBrowser) {
    oscrollerDom.value = document.querySelector('#app > .o-scroller > .o-scroller-container');
    oscrollerDom.value?.addEventListener('scroll', listenScroll);
  }
  lastSearchValue.value = searchValue.value;
  const node = tree.value.getNode(tree.value.root, activeVal.value);
  expand(node);
});

onUnmounted(() => {
  oscrollerDom.value?.removeEventListener('scroll', listenScroll);
});

// -------------------- 点击菜单跳转文档 --------------------
const goToPage = (href: string | undefined) => {
  if (href) {
    if (href.startsWith('http')) {
      openWindow(href);
    } else {
      router.go(href);
      useSearchingStore().isSearching = false;
    }
  }

  if (size.width < 1200) {
    emit('switchVisible');
  }
};
</script>

<template>
  <aside class="doc-menu" :style="{ height: height }">
    <div class="menu-wrapper">
      <OScroller show-type="hover" size="small">
        <OMenu v-model="activeVal" v-model:expanded="expandedArr" accordion>
          <template v-for="(tree, treeIdx) in treeList" :key="treeIdx">
            <div v-for="chapter in tree.root.children" :key="chapter.id" class="chapter-item">
              <DocSubMenu :data="chapter" @change-sidebar="goToPage" :depth="1" />
            </div>
          </template>
        </OMenu>
      </OScroller>
    </div>
  </aside>
</template>

<style lang="scss" scoped>
.o-scroller {
  height: 100%;
  padding-bottom: 32px;
}

.doc-menu {
  height: calc(100% - 62px);
}

.menu-wrapper {
  height: 100%;
  padding-right: calc(var(--grid-column-gutter) / 2);
  .o-scroller {
    padding-right: calc(var(--grid-column-gutter) / 2);
  }
}

.chapter-item {
  :deep(.o-sub-menu) {
    &.menu-level-1 {
      & > .o-sub-menu-title {
        @include text2;
        font-weight: 500;
        margin-left: 4px;
        padding-top: 9px;
        padding-bottom: 9px;
      }
    }
    .o-sub-menu-title {
      padding-left: 7px;
    }
  }
}

.o-menu {
  --menu-padding-v: 7px;
  --menu-padding-h: 7px;
  --menu-width: 100%;
}

.o-sub-menu {
  --sub-menu-color: var(--o-color-info2);
  --sub-menu-text-size: 16px;
  --sub-menu-text-height: 24px;
}

:deep(.o-menu) {
  .o-sub-menu-title-arrow {
    color: var(--o-color-info2);
  }
}
:deep(.o-sub-menu-children) {
  margin-left: 12px;
  border-left: 1px solid var(--o-color-control4);
  padding-left: 3px;
  overflow: initial;
  transition: none;
  .o-sub-menu-title {
    padding-left: var(--menu-padding-h) !important;
  }
}
</style>
